<template>
  <div class="app-container">
    <el-form :inline="true" ref="refForm" :model="form">
      <el-form-item label="查询时间" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="代理账号：" prop="proxy">
        <el-input v-model="form.proxy" type="String" @keyup.enter.native="submitFilterForm"></el-input>
      </el-form-item>
      <!--<el-form-item label="域名地址：">-->
      <!--<el-select v-model="form.domain" style="width: 120px;">-->
      <!--<el-option-->
      <!--v-for="item in domainList"-->
      <!--:value="item.value"-->
      <!--:label="item.title"-->
      <!--:key="item.value"-->
      <!--&gt;</el-option>-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="submitFilterForm">搜索</el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-download" @click="exportHandle">导出</el-button>
        <el-button @click="resetForm('refForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      border
      :data="tableData"
      v-loading="loading"
      element-loading-text="加载中..."
      show-summary
      :summary-method="getSummaries"
      class="el-table-align-center">
      <el-table-column label="时间" prop="date" width="180" align="center">
      </el-table-column>
      <el-table-column prop="ip" label="独立用户访问量" align="center"></el-table-column>
      <el-table-column prop="reg" label="注册用户量" align="center"></el-table-column>
      <el-table-column prop="regRate" label="注册率" align="center">
        <template slot-scope="{row}" v-if="row.ip!=0">
          {{(row.reg/row.ip)*100 | currency}}%
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>


<script>
import { getRegisterRateApi as listApi, exportRegisterRate } from '@/services/api/operational';
import { grid } from '@/build';

export default {
  name: 'register-rate',
  mixins: [grid],
  data() {
    // let times = _.toPeriod({
    //   start: [-1, 'days'],
    //   end: [0, 'days'],
    //   format: 'YYYY-MM-DD'
    // });
    // 本月时间本月1号至当前时间
    const monthTime = [moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')];

    return {
      tableData: [],
      domainList: [
        {
          value: '1',
          title: 'www.google.com',
        },
        {
          value: '2',
          title: 'www.baidu.com',
        },
      ],
      form: {
        time: monthTime,
        proxy: undefined,
        domain: undefined,
      },
      filters: {
        stime: moment(monthTime[0]).valueOf(),
        etime: moment(monthTime[1]).valueOf() + 86399999,
      },
      pickerOptions: {
        disabledDate: time => moment(time).valueOf() < moment(moment().subtract(30, 'days')).valueOf() || moment(time).valueOf() > Date.now(),
      },
    };
  },
  methods: {
    selfResetForm(formName) {
      this.resetForm(formName);
      this.submitFilterForm();
    },
    submitFilterForm() {
      const { time, proxy, domain } = this.form;
      let stime;
      let etime;
      if (!_.isUndefined(time) && _.isArray(time)) {
        stime = moment(time[0]).valueOf();
        etime = moment(time[1]).valueOf() + 86399999;
      }
      this.filters = {
        stime, etime, proxy, domain, project: consts.PLATFROM_PREFIX,
      };
      this.gridSearch();
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]));
        if (index === 0) {
          sums[index] = '汇总';
          return;
        } if ([1, 2].indexOf(index) !== -1 && !values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            }
            return prev;
          }, 0);
        } else if (index == 3) {
          // sums[index] = _.formatDiv(sums[2], (sums[1] ? sums[1] : 1), {fixed: 2});
          sums[index] = '';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 导出
    exportHandle() {
      const {
        stime, etime, proxy, page,
      } = this.filters;
      const ajaxData = {
        stime, etime, proxy, page,
      };
      const filename = '注册率分析明细报表.csv';
      const header = ['时间', '独立用户访问量', '注册用户量', '注册率'];
      const filterField = ['date', 'ip', 'reg', 'regRate'];
      exportRegisterRate(ajaxData).then(([result, data]) => {
        if (result) {
          const exportData = this.responseFormatter(data);
          console.log(exportData);
          // return
          this.export2Excel(header, filterField, exportData, filename);
        } else {
          this.$message({ message: `导出失败,${data.message}`, type: 'warning' });
        }
      });
    },
    responseFormatter(data) {
      const result = [];
      let sortData = [];
      const endData = [];
      _.forIn(data, (value, key) => {
        result.push({ ...value, date: key });
      });
      sortData = _.sortBy(result, item => item.date);
      sortData.reverse();
      sortData.forEach((item) => {
        endData.push({
          date: item.date,
          ip: item.ip,
          reg: item.reg,
          regRate: item.ip !== 0 ? `${_.currency((item.reg / item.ip) * 100)}%` : '',
        });
      });

      return endData;
    },
  },
  mounted() {
    this.bindGet(listApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      format: (data) => {
        const result = [];
        let sortData = [];
        _.forIn(data, (value, key) => {
          result.push({ ...value, date: key });
        });
        sortData = _.sortBy(result, item => item.date);
        return sortData.reverse();
      },
    });
    this.submitFilterForm();
  },

};
</script>

<style scoped>

</style>
